import {ref} from 'vue';
import eventBus from "@/utils/eventBus.ts";
// 标志位区分是手动断开还是意外断开
let isManualDisconnect = false;



export const useWebSocket = {
  socket: null as WebSocket | null, // 声明
  isConnected: ref(false), // 判断当前连接状态
  reconnectAttempts: 0, // 默认重连数
  maxReconnectAttempts: 5, // 最大重连数
  reconnectInterval: 3000, // 重连间隔

  // 连接 WebSocket 服务器,监听相关事件
  connect(url: string) {
    if (useWebSocket.socket) {
      return
    }
    useWebSocket.socket = new WebSocket(url)

    useWebSocket.socket.onopen = () => {
      useWebSocket.isConnected.value = true;
      useWebSocket.reconnectAttempts = 0;
      console.log('WebSocket连接已打开');
    };

    useWebSocket.socket.onclose = () => {
      useWebSocket.isConnected.value = false;
      console.log('WebSocket连接已关闭');
      if (!isManualDisconnect) {
        useWebSocket.reconnect();
      }
    };

    useWebSocket.socket.onerror = (error: Event) => {
      console.error('WebSocket error:', error);
    };

    useWebSocket.socket.onmessage = (event: MessageEvent) => {
      try {
        const jsonObj = JSON.parse(event.data);
        console.log('收到websocket消息:', jsonObj);
        openElNotification(jsonObj);
      } catch (e) {
        console.error("JSON字符串格式错误:", e);
      }
    };
  },
  // 关闭链接
  disconnect() {
    isManualDisconnect = true
    if (useWebSocket.socket) {
      useWebSocket.socket.close();
      useWebSocket.socket = null;
      useWebSocket.isConnected.value = false;
    }
  },
  // 尝试重连
  reconnect() {
    if (isManualDisconnect) {
      console.log('Manual disconnect, no reconnect needed');
      return;
    }
    if (useWebSocket.reconnectAttempts < useWebSocket.maxReconnectAttempts) {
      useWebSocket.reconnectAttempts++;
      console.log(`Reconnecting attempt ${useWebSocket.reconnectAttempts}`);
      setTimeout(() => {
        useWebSocket.connect(useWebSocket.socket?.url || '');
      }, useWebSocket.reconnectInterval);
    } else {
      console.error('Max reconnect attempts reached');
    }
  },
  // 发送消息
  sendMessage(message: string) {
    if (useWebSocket.isConnected.value && useWebSocket.socket) {
      useWebSocket.socket.send(message);
      console.log('WebSocket客户端发送的消息:', message);
    } else {
      console.error('WebSocket is not connected');
    }
  },
}

/**
 * 消息提示组件点击事件
 * @param jsonObj
 */
function openElNotification(jsonObj: any) {
  let businessType = "";
  if (jsonObj.businessType === "transmitOrder") {
    businessType = "医嘱传输";
    // 发送事件
    eventBus.emit('loadMessage', jsonObj);
  }
  ElNotification({
    title: `${businessType}`,
    zIndex: 9,
    dangerouslyUseHTMLString: true,
    offset: 50,
    message: `<span style="color: #b20202">${jsonObj.message}</a>`,
    onClick() {
      transmitOrderClick(jsonObj);
    },
  })
}

function transmitOrderClick(jsonObj) {
  console.log(jsonObj);
  // router.replace({path: "/nurse/patientManage/patientBedRecCard"});
}
